package com.ruoyi.ai.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.ai.domain.bo.WxUserBo;
import com.ruoyi.ai.domain.vo.WxUserVo;
import com.ruoyi.ai.domain.WxUser;
import com.ruoyi.ai.mapper.WxUserMapper;
import com.ruoyi.ai.service.IWxUserService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 微信用户Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-23
 */
@RequiredArgsConstructor
@Service
public class WxUserServiceImpl implements IWxUserService {

    private final WxUserMapper baseMapper;

    /**
     * 查询微信用户
     */
    @Override
    public WxUserVo queryById(Long wxUserId) {
        return baseMapper.selectVoById(wxUserId);
    }

    /**
     * 查询微信用户列表
     */
    @Override
    public TableDataInfo<WxUserVo> queryPageList(WxUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WxUser> lqw = buildQueryWrapper(bo);
        Page<WxUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询微信用户列表
     */
    @Override
    public List<WxUserVo> queryList(WxUserBo bo) {
        LambdaQueryWrapper<WxUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WxUser> buildQueryWrapper(WxUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WxUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOpenid()), WxUser::getOpenid, bo.getOpenid());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), WxUser::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), WxUser::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getWxNo()), WxUser::getWxNo, bo.getWxNo());
        lqw.between(params.get("beginRegisterTime") != null && params.get("endRegisterTime") != null,
            WxUser::getRegisterTime, params.get("beginRegisterTime"), params.get("endRegisterTime"));
        lqw.eq(bo.getStatus() != null, WxUser::getStatus, bo.getStatus());
        lqw.eq(bo.getMemberStatus() != null, WxUser::getMemberStatus, bo.getMemberStatus());
        return lqw;
    }

    /**
     * 新增微信用户
     */
    @Override
    public Boolean insertByBo(WxUserBo bo) {
        WxUser add = BeanUtil.toBean(bo, WxUser.class);
        add.setDelFlag(UserConstants.DEL_FLAG_FALSE);
        if (add.getMemberStatus() == null) {
            add.setMemberStatus(UserConstants.MEMBER_STATUS_FALSE);
        }
        WxUser wxUser = this.queryByOpenid(bo.getOpenid());
        if (wxUser != null) {
            throw new ServiceException("openid已存在");
        }
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setWxUserId(add.getWxUserId());
        }
        return flag;
    }

    /**
     * 修改微信用户
     */
    @Override
    public Boolean updateByBo(WxUserBo bo) {
        WxUser update = BeanUtil.toBean(bo, WxUser.class);
        WxUser wxUser = this.queryByOpenid(bo.getOpenid());
        if (wxUser != null && !Objects.equals(wxUser.getWxUserId(), bo.getWxUserId())) {
            throw new ServiceException("openid已存在");
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WxUser entity) {
        //TODO 做一些数据校验,如唯一约束

    }

    /**
     * 批量删除微信用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public WxUser queryByOpenid(String openid) {
        LambdaQueryWrapper<WxUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(WxUser::getOpenid, openid);
        List<WxUser> wxUsers = baseMapper.selectList(lqw);
        if (CollectionUtils.isNotEmpty(wxUsers)) {
            return wxUsers.get(0);
        }
        return null;
    }

    @Override
    public WxUser queryByUnionId(String unionId) {
        LambdaQueryWrapper<WxUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(WxUser::getUnionid, unionId);
        List<WxUser> wxUsers = baseMapper.selectList(lqw);
        if (CollectionUtils.isNotEmpty(wxUsers)) {
            return wxUsers.get(0);
        }
        return null;
    }

    @Override
    public Boolean updateNumWithNull(WxUserBo bo) {
        int update = baseMapper.update(new UpdateWrapper<WxUser>().lambda()
            .eq(WxUser::getWxUserId, bo.getWxUserId())
            .set(WxUser::getChatNum, bo.getChatNum())
            .set(WxUser::getOcrNum, bo.getOcrNum())
            .set(WxUser::getVoiceNum, bo.getVoiceNum())
            .set(WxUser::getMemberStatus, bo.getMemberStatus())
            .set(WxUser::getMemberGradeId, bo.getMemberGradeId())
            .set(WxUser::getUpdateTime, bo.getUpdateTime())
        );
        return update > 0;
    }
}
